#include "Settings.h"
#include "common.h"

QString QCMSettings::DefaultSettingsPath()
{
#ifdef Q_WS_S60
    return "C:\\private\\" UIDSTRING "\\settings.dat";
#else
    return ".\\settings.dat";
#endif
}

QCMSettings::QCMSettings() : iStoreOnExit(true), iAutoStore(false)
{
    iSettingsPath = DefaultSettingsPath();
    Load();
}

QCMSettings::QCMSettings(const QString &path) : iStoreOnExit(true), iAutoStore(false)
{
    iSettingsPath = path;
    Load();
}

QCMSettings::~QCMSettings()
{
    if(iStoreOnExit)
        Store();
}

bool QCMSettings::Load()
{
    QFile file(iSettingsPath);
    if(!file.open(QFile::ReadOnly))
        return false;
    while(file.canReadLine())
    {
        QByteArray arr = file.readLine();
        QList<QByteArray> al = arr.split('|');
        if(al.count() < 2)
            iSettingsMap.insert(QString(al[0]), QString::null);
        iSettingsMap.insert(QString(al[0]), QString(al[1]));
    }
    file.close();
    return true;
}

bool QCMSettings::Store()
{
    QFile file(iSettingsPath);
    if(!file.open(QFile::ReadWrite | QFile::Truncate))
        return false;
    for(QMap<QString, QString>::iterator i = iSettingsMap.begin(); i != iSettingsMap.end(); ++i)
    {
        QByteArray arr = (QString("%1|%2\r\n").arg(i.key()).arg(i.value())).toUtf8();
        file.write(arr);
    }
    file.close();
    return true;
}

static QCMSettings* g_globalSettings = NULL;

void QCMSettings::InstallSettings(QCMSettings *settings)
{
    g_globalSettings = settings;
}

QCMSettings* QCMSettings::Current()
{
    return g_globalSettings;
}

void QCMSettings::Set(const QString &aKey, const QString &aValue)
{
    iSettingsMap[aKey] = aValue;
    if(iAutoStore)
        Store();
}

QString QCMSettings::Get(const QString &aKey, const QString &aDefaultValue)
{
    if(iSettingsMap.contains(aKey))
        return iSettingsMap[aKey];
    else return aDefaultValue;
}


